package com.cyzy.controller;

import com.cyzy.entity.ApiResponse;
import com.cyzy.entity.EmailLoginRequest;
import com.cyzy.entity.UserInfo;
import com.cyzy.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;

/**
 * @author LIGHT
 */
@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    private EmailService emailService;

    @GetMapping("/send")
    public ApiResponse<Void> sentEmail() {
        try {
            emailService.sentEmail("nannan@sunan.online", "测试邮件", "测试邮件");
            return ApiResponse.success("发送邮件成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error("发送邮件失败: " + e.getMessage());
        }
    }

    /**
     * 发送邮箱验证码
     * 
     * @param email 邮箱地址
     * @return 结果
     */
    @GetMapping("/code")
    public ApiResponse<Void> sendVerificationCode(@RequestParam("email") String email) {
        try {
            emailService.sendVerificationCode(email);
            return ApiResponse.success("验证码发送成功", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.error("验证码发送失败: " + e.getMessage());
        }
    }

    /**
     * 验证邮箱验证码
     * 
     * @param email 邮箱地址
     * @param code  验证码
     * @return 结果
     */
    @PostMapping("/code/verify")
    public ApiResponse<Void> verifyCode(@RequestParam String email, @RequestParam String code) {
        boolean verified = emailService.verifyCode(email, code);
        if (verified) {
            return ApiResponse.success("验证成功", null);
        } else {
            return ApiResponse.error(400, "验证失败，验证码错误或已过期");
        }
    }

    /**
     * 邮箱验证码登录
     * 
     * @param request 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public ApiResponse<UserInfo> login(@RequestBody EmailLoginRequest request) {
        boolean verified = emailService.verifyCode(request.getEmail(), request.getCode());
        if (verified) {
            // 验证成功，这里可以生成token或者调用其他服务进行用户信息查询
            // 模拟用户信息，实际项目中应该从数据库获取
            UserInfo userInfo = new UserInfo(
                    UUID.randomUUID().toString().replace("-", ""),
                    request.getEmail().split("@")[0],
                    request.getEmail(),
                    "https://avatar.example.com/default.png");
            return ApiResponse.success("登录成功", userInfo);
        } else {
            return ApiResponse.error(400, "登录失败，验证码错误或已过期");
        }
    }
}
